<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="item" prop="item">
        <!-- <el-input
          v-model="queryParams.item"
          placeholder="请输入item"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select
          v-model="queryParams.item"
          clearable
          filterable
          remote
          :remote-method="getDatas"
          :loading="loading"
          placeholder="请输入item"
        >
          <el-option
            v-for="item in options"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品类" prop="productType">
        <el-input v-model="queryParams.productType" placeholder="品类" />
      </el-form-item>
      <el-form-item label="应用时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择应用时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['conf:ProTypeConf:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['conf:ProTypeConf:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['conf:ProTypeConf:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['conf:ProTypeConf:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" plain icon="el-icon-upload" @click="daoru"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" @click="opensyncInfo = true"
          >同步品类数据</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="openitem = true"
          >同步item</el-button
        >
      </el-col> -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-dialog
      :visible.sync="opensyncInfo"
      width="700px"
      append-to-body
      title="选择时间"
    >
      <timeSearch
        @getDateArr="getDateArr"
        @changDay="changDay"
        :timeArr="timeArr"
        :dayActive="this.dayActive"
        :dayLimit="1095"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlesyncProductType"
          >同步品类数据</el-button
        >
        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="openitem"
      width="700px"
      append-to-body
      title="选择时间"
    >
      <timeSearch
        @getDateArr="getDateArr"
        @changDay="changDay"
        :timeArr="timeArr"
        :dayActive="this.dayActive"
        :dayLimit="1095"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlesyncBiLiveTalentItem"
          >同步item</el-button
        >
        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
    </el-dialog>

    <el-table
      v-loading="loading"
      :data="ProTypeConfList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="item" align="center" prop="item" />
      <el-table-column label="品类" align="center" prop="productType" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['conf:ProTypeConf:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['conf:ProTypeConf:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品类配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      v-if="open"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="item" prop="item">
          <!-- <el-input v-model="form.item" placeholder="请输入item" /> -->
          <el-select
            v-model="form.item"
            clearable
            filterable
            remote
            :remote-method="getDatas"
            :loading="loading"
            placeholder="请输入item"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品类" prop="productType">
          <el-input v-model="form.productType" placeholder="品类" />
        </el-form-item>
        <el-form-item label="时间设置" prop="startTime">
          <!-- :picker-options="{
              disabledDate: (time) =>
                !(
                  time.getTime() >= Date.now() - 365 * 8.64e7 &&
                  time.getTime() < Date.now() - 8.64e7
                ),
            }" -->
          <el-date-picker
            key="daterange"
            v-model="rangeDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 240px"
            @change="handleChange"
            size="mini"
          />
        </el-form-item>
        <!-- <el-form-item label="应用时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择应用时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
    <el-dialog
      title="导入"
      :visible.sync="dialogVisible"
      width="500px"
      append-to-body
      v-if="dialogVisible"
    >
      <el-form label-width="150px">
        <el-form-item label="导入模板下载" prop="file">
          <el-button size="mini" @click="downLoadFile"> 模板下载 </el-button>
        </el-form-item>
        <el-form-item label="导入文件" prop="file">
          <el-upload
            ref="daoru"
            :action="Upload.url"
            :headers="Upload.headers"
            :limit="limit"
            :on-exceed="handleExceed"
            :on-success="handlePictureSuccessPic"
            :before-upload="beforeAvatarUpload"
            :file-list="fileLi"
            :on-change="changeFile1"
          >
            <el-button size="mini" plain icon="el-icon-upload"
              >批量导入</el-button
            >

            <!-- <i class="el-icon-plus"></i> -->
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title=""
      :visible.sync="openInfo"
      width="1000px"
      append-to-body
      v-if="openInfo"
    >
      <h2>
        部分导入成功，以下导入失败，<br />原因：货品定义时间有冲突，请检查！
      </h2>
      <el-table :data="dialogVisibleList">
        <el-table-column label="item" align="center" prop="item" />
        <el-table-column label="品类" align="center" prop="productType" />
        <el-table-column
          label="开始时间"
          align="center"
          prop="startTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="结束时间"
          align="center"
          prop="endTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import timeSearch from "@/common/day";
import { productNoLike, selectItemList } from "@/api/product/template";
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
} from "@/api/data/template";
import {
  listProTypeConf,
  getProTypeConf,
  delProTypeConf,
  addProTypeConf,
  updateProTypeConf,
} from "@/api/conf/ProTypeConf";
import { syncProductType } from "@/api/live/BiLiveOrder";
import { syncBiLiveTalentItem } from "@/api/live/BiLiveTalent";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  name: "ProTypeConf",
  components: { timeSearch },
  data() {
    return {
      openitem: false,
      dayActive: 2,
      timeArr: [
        { value: "2", label: "昨天" },
        { value: "7", label: "最近7天" },
        { value: "30", label: "最近30天" },
        { value: "365", label: "最近一年" },
        { value: "1", label: "日" },
      ],
      timeGap: { startTime: "", endTime: "" },
      opensyncInfo: false,
      options: [],
      openInfo: false,
      dialogVisibleList: [],
      fileLi: [],
      dialogVisible: false,
      limit: 2,
      Upload: {
        // 设置上传的请求头部
        headers: {
          header: { responseType: "blob" },

          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/conf/ProTypeConf/importData",
      },
      //结束/应用时间
      rangeDate: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品类配置表格数据
      ProTypeConfList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        item: null,
        productType: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    selectItemList({ item: "" }).then((res) => {
      this.options = res;
    });
  },
  methods: {
    //时间控件
    changDay(val) {
      this.dayActive = val;
      this.timeGap.startTime = val[0];
      this.timeGap.endTime = val[1];
    },
    getDateArr(value) {
      this.timeGap.startTime = value[0];
      this.timeGap.endTime = value[1];
      console.log(JSON.stringify(this.timeGap));
      this.dayActive = 1;
    },
    // 打开加载层
    openLoading1() {
      this.$modal.loading("正在加载数据，请稍候！");
    },
    handlesyncBiLiveTalentItem() {
      // this.$modal.msgWarning("数据正在同步，请稍候");

      const obj = {
        startDate: this.timeGap.startTime,
        endDate: this.timeGap.endTime,
      };
      this.openLoading1();
      syncBiLiveTalentItem(obj).then(() => {
        this.$modal.msgSuccess("同步数据成功");
        this.$modal.closeLoading();
        this.openitem = false;
        this.getList();

        // this.$store.dispatch('dict/cleanDict');
      });
    },
    handlesyncProductType() {
      // this.$modal.msgWarning("数据正在同步，请稍候");

      const obj = {
        startDate: this.timeGap.startTime,
        endDate: this.timeGap.endTime,
      };
      this.openLoading1();
      syncProductType(obj).then(() => {
        this.$modal.msgSuccess("同步数据成功");
        this.$modal.closeLoading();
        this.opensyncInfo = false;
        this.getList();

        // this.$store.dispatch('dict/cleanDict');
      });
    },
    /* 获取货号列表 */
    getDatas(key) {
      console.log(JSON.stringify(key));
      this.loading = true;
      // return
      selectItemList({ item: key }).then((res) => {
        this.loading = false;
        this.options = res;
        console.log(JSON.stringify(this.options));
      });
    },
    downLoadFile() {
      let obj = {
        templateName: "达播品类配置",
      };
      listTemplate(obj).then((response) => {
        window.location.href =
          process.env.VUE_APP_BASE_API + response.rows[0].templateUrl;
      });
    },
    handleChange() {
      this.form.endTime = this.rangeDate[1];
      this.form.startTime = this.rangeDate[0];
      // this.getList();
    },
    /** 查询品类配置列表 */
    getList() {
      this.loading = true;
      listProTypeConf(this.queryParams).then((response) => {
        this.ProTypeConfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        item: null,
        productType: null,
        startTime: null,
        endTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品类配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProTypeConf(id).then((response) => {
        this.form = response.data;
        this.rangeDate = [this.form.startTime, this.form.endTime];
        this.open = true;
        this.title = "修改品类配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.endTime = this.rangeDate[1];
      this.form.startTime = this.rangeDate[0];
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateProTypeConf(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.rangeDate = [];
            });
          } else {
            addProTypeConf(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.rangeDate = [];
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除品类配置编号为"' + ids + '"的数据项？')
        .then(function () {
          return delProTypeConf(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "conf/ProTypeConf/export",
        {
          ...this.queryParams,
        },
        `ProTypeConf_${new Date().getTime()}.xlsx`
      );
    },

    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }
      this.openUploadLoading();
      return isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.picUrl = file.url;
      this.imageUrl = file.url;
      // this.dialogVisible = true;
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    // 打开加载层
    openUploadLoading() {
      this.$modal.loading("正在导入，请稍候！");
    },
    //文件导入成功回传

    handlePictureSuccessPic(response, file) {
      this.$refs.daoru.clearFiles(); //去掉文件列表
      this.$modal.closeLoading();
      console.log(JSON.stringify(file));
      console.log(JSON.stringify(response));
      this.openInfo = true;
      this.dialogVisibleList = response;
      // if (response.code == 200) {

      //   this.$modal.msgSuccess("导入成功");
      //   this.getList();
      // }

      // this.openmsg = true;
      // this.msg = response.msg;

      //设置图片访问路径 （url 后台传过来的的上传地址）
      // this.picUrl = file.response.url;
      // const url = file.response.fileName;
      // this.file = file.response.url;
      // console.log(JSON.stringify(this.file));
      // if (res.code == 200) {

      //   this.dialogVisible = false

      //   if (res.msg == '操作成功') {

      //     this.$modal.msgSuccess('导入成功')
      //   } else {
      //     this.$modal.msgError(res.msg);
      //   }
      //   this.getList();
      //   // return true
      // } else {
      //   this.$modal.msgError(res.msg);
      //   this.dialogVisible = true
      //   // this.$message.msgError('该颜色未在字典定义')
      //   return
      // }
    },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传文件让第二次覆盖第一的文件
    changeFile1(file, fileList) {
      if (fileList.length > 1) {
        this.fileLi = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
  },
};
</script>
